package com.SmartCare.service.impl.health;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.SmartCare.common.Result;
import com.SmartCare.common.vo.health.BloodPressureVo;
import com.SmartCare.common.vo.health.BloodPressuresVo;
import com.SmartCare.mapper.health.BloodPressureMapper;
import com.SmartCare.pojo.health.BloodPressure;
import com.SmartCare.service.health.BloodPressureService;
import com.SmartCare.utils.DateTimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class BloodPressureServiceImpl extends ServiceImpl<BloodPressureMapper,BloodPressure> implements BloodPressureService {
    /**
     * 查询一周血压记录
     *
     * @param elderlyId
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Result bloodPressureQuery(Long elderlyId, String startTime, String endTime) {
        if (elderlyId==null) {
            return Result.error("未知错误");
        }
        //构造查询条件
        LambdaQueryWrapper<BloodPressure> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(BloodPressure::getCreatedTime,startTime,endTime);
        queryWrapper.eq(BloodPressure::getElderlyId,elderlyId);
        queryWrapper.orderByAsc(BloodPressure::getCreatedTime);
        //执行
        List<BloodPressure> list = super.list(queryWrapper);

        BloodPressuresVo pressuresVo = new BloodPressuresVo();

        List<BloodPressureVo> voList = new ArrayList<>();

        for (BloodPressure item : list) {
            BloodPressureVo pressureVo = new BloodPressureVo();
            BeanUtils.copyProperties(item, pressureVo,"createdTime");

            pressureVo.setCreatedTime(DateTimeUtils.formatDateTime(item.getCreatedTime()));

            voList.add(pressureVo);
        }
        pressuresVo.setBloodPressure(voList);
        if (pressuresVo.getBloodPressure().isEmpty()){
            return Result.success("无记录");
        }
        return Result.success("查询成功",pressuresVo);
    }

    @Override
    public Result bloodPressureAdd(Long elderlyId, Float systolicPressure, Float diastolicPressure) {
        if (elderlyId==null) {
            return Result.error("未知错误");
        }

        BloodPressure bloodPressure = BloodPressure.builder()
                .elderlyId(elderlyId)
                .systolicPressure(systolicPressure)
                .diastolicPressure(diastolicPressure)
                .build();

        boolean res = save(bloodPressure);
        if (!res) {
            return Result.error("添加失败");
        }
        return Result.success("添加成功");
    }
}
